package pers.qianyu.backup.controller;

import cn.hutool.core.io.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.web.bind.annotation.*;
import pers.qianyu.backup.constants.*;
import pers.qianyu.backup.exception.*;
import pers.qianyu.backup.service.*;
import pers.qianyu.core.http.*;

import java.io.*;
import java.time.*;
import java.time.format.*;
import java.util.*;

/**
 * 数据库备份接口
 *
 * @author mizzle rain
 * @date 2020-10-27 14:16
 */
@RestController
@RequestMapping("/backup")
public class BackupController {
    @Autowired
    BackupService mysqlBackupService;

    @GetMapping("/")
    public HttpResult<?> backup() {
        String backupFolderName = BackupConstants.DEFAULT_BACKUP_NAME + "_" +
                LocalDateTime.now().format(DateTimeFormatter.ofPattern(BackupConstants.DATE_FORMAT));
        return backup(backupFolderName);
    }

    private HttpResult<?> backup(String backupFolderName) {
        String filePath = BackupConstants.BACKUP_FOLDER + backupFolderName +
                File.separator + BackupConstants.BACKUP_FILE_NAME;
        boolean success = mysqlBackupService.backup(filePath);
        if (!success) {
            return HttpResult.error(BackupLambErrorCodeEnum.BACKUP_FAILED);
        }
        return HttpResult.ok().setMessage("数据备份成功");
    }

    @GetMapping("/restore")
    public HttpResult<?> restore(@RequestParam String name) {
        boolean success = mysqlBackupService.restore(BackupConstants.RESTORE_FOLDER + name);
        if (!success) {
            return HttpResult.error(BackupLambErrorCodeEnum.RESTORE_FAILED);
        }
        return HttpResult.ok().setMessage("数据恢复成功");
    }

    @GetMapping("/records")
    public HttpResult<List<Map<String, String>>> findBackupRecords() {
        if (!new File(BackupConstants.DEFAULT_RESTORE_FILE).exists()) {
            // 初始默认备份文件
            backup(BackupConstants.DEFAULT_BACKUP_NAME);
        }
        List<Map<String, String>> backupRecords = new ArrayList<>();
        File restoreFolderFile = new File(BackupConstants.RESTORE_FOLDER);
        for (File file : restoreFolderFile.listFiles()) {
            Map<String, String> backup = new HashMap<>();
            backup.put("name", file.getName());
            backup.put("title", file.getName());
            if (BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(file.getName())) {
                backup.put("title", "系统默认备份");
            }
            backupRecords.add(backup);
        }
        // 排序，默认备份最前，然后按时间戳排序，新备份在前面
        backupRecords.sort((o1, o2) -> BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(o1.get("name")) ? -1
                : BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(o2.get("name")) ? 1 : o2.get("name").compareTo(o1.get("name")));
        return HttpResult.ok(backupRecords);
    }

    @DeleteMapping("/")
    public HttpResult<?> deleteBackupRecord(@RequestParam String name) {
        if (BackupConstants.DEFAULT_BACKUP_NAME.equals(name)) {
            return HttpResult.error("系统默认备份无法删除!");
        }
        String restoreFilePath = BackupConstants.BACKUP_FOLDER + name;
        FileUtil.del(restoreFilePath);
        return HttpResult.ok().setMessage("备份删除成功");
    }
}
